package bigbrother.service;

import java.sql.Connection;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import bigbrother.dao.EmployeeDao;
import bigbrother.dao.WorkLogDao;
import bigbrother.entity.Employee;
import bigbrother.entity.WorkLog;
import bigbrother.exception.ServiceFailException;
import bigbrother.util.ConnectionHandler;

public class EmployeeService implements IEmployeeService {
	Logger logger = LogManager.getLogger(EmployeeService.class);
	EmployeeDao eDao = EmployeeDao.getDao();
	WorkLogDao wDao = WorkLogDao.getDao();
	
	private static EmployeeService service;
	
	private EmployeeService(){}
	
	public static EmployeeService getService(){
		if(service==null){
			service = new EmployeeService();
		}
		return service;
	}
	
	@Override
	public void hireEmployee(Employee emp) {
		// 아래 작업을 하나의 작업으로 묶어야 한다. --> 하나의 connection
		ConnectionHandler ch = ConnectionHandler.getHandler();
		Connection con = null;
		
		try {
			con = ch.getConnection();
			logger.trace(con);
			con.setAutoCommit(false);
			eDao.addEmployee(con, emp);
			logger.trace(emp+" 저장 완료");
			WorkLog log = new WorkLog();
			log.setEmployee(emp.getId());
			log.setWork("고용");
			wDao.addWorkLog(con, log);
			logger.trace(log+" 저장 완료");
			con.commit();
		} catch (Exception e) {
			logger.error(e);
			ch.rollback(con);
			throw new ServiceFailException(e);
		}finally{
			logger.trace(con);
			ch.setCommit(con, true);
			ch.close(con);
		}
	}

	@Override
	public void fierEmployee(String id) {
		ConnectionHandler ch = ConnectionHandler.getHandler();
		Connection con = null;
		try {
			con = ch.getConnection();
			con.setAutoCommit(false);
			wDao.deleteWorkLog(con, id);
			eDao.deleteEmployee(con, id);
			con.commit();
		} catch (Exception e) {
			logger.error(e);
			ch.rollback(con);
			throw new ServiceFailException(e);
		}finally{
			ch.setCommit(con, true);
			ch.close(con);
		}
	}
	@Override
	public boolean canUseId(String id) {
		ConnectionHandler ch = ConnectionHandler.getHandler();
		Connection con = null;
		boolean result = false;
		try {
			con = ch.getConnection();
			Employee emp = eDao.getEmployee(con, id);
			logger.trace(emp);
			result = emp==null? true:false;
		} catch (Exception e) {
			logger.error(e);
			throw new ServiceFailException(e);
		}finally{
			ch.close(con);
		}
		logger.trace(result);
		return result;
	}
}
